# -*- coding: utf-8 -*-

import re

from odoo.http import request
from furl import urljoin, furl

sentinel = object()

RE_IMAGE_SRC = re.compile(r'(/web/image/\d+/)')
ATTACHMENT_URL_PREFIX = '/web/image/'
CONTENT_URL_PREFIX = '/web/image/'


def sanitize_html_field(content, host_url=None):
    if host_url is None:
        host_url = request.httprequest.host_url
    return re.sub(RE_IMAGE_SRC, lambda m: urljoin(host_url, m.group(1)), content)


def convert_to_attachment_url(attachment_id, url_prefix=ATTACHMENT_URL_PREFIX, host_url=None):
    if attachment_id.__class__.__name__ == 'ir.attachment':
        attachment_id = attachment_id[0].id
    if host_url is None:
        host_url = request.httprequest.host_url
    url = urljoin(host_url, url_prefix)
    url = urljoin(url, str(attachment_id))
    return url

def convert_to_video_url(entry_id, model_xmlid, field, filename_field, url_prefix=CONTENT_URL_PREFIX, host_url=None):
    if host_url is None:
        host_url = request.httprequest.host_url
    url = urljoin(host_url, url_prefix)
    url = furl(url)
    url.args = {
        'model': model_xmlid,
        'id': entry_id,
        'field': field,
        'filename_field': filename_field,
    }
    return url.url
